/**
 * @Author: 陈瑞鹏
 * @Date:   2022-12-09 18:02:27
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2023-09-25 09:09:37
 */
import abiao_utils from "abiao_utils";
import express, { json } from "express";
import { Code } from "../enum/code.enum";
import JWT from "../utils/jwt";
import Result from "../utils/result";
import utils from "../utils/utils";
import Barrack from "./barrack.model";
import Email from "./email.model";
import Exchange from "./exchange.model";
import ExchangeLog from "./exchangeLog.model";
import GBag from "./gBag.model";
import GSign from "./gSign.model";
import guard from "./guard.controller";
import GUser from "./gUser.model";
import Treasure from "./treasure.model";
import Victory from "./victory.model";
import GDailyTask from "./gDailyTask.model";
import reward from '../controllers/reward.controller';
import Redis from "../utils/redis";
import { AnyArray } from "mongoose";
const guardRoute = express.Router();
guardRoute.post("/enterGame", async (req, res) => {
  let { openId, avatar, nickName, serverId, gameUrl, ecid, time, sign, evaluate } = req.body;

  let ip: string = utils.getClientIp(req);

  let endRole: any = await GUser.findOne({}).sort({ roleId: -1 });

  let UserRes: any = await GUser.findOne({ openId });

  let roleId: number;

  if (!UserRes) {
    roleId = !endRole ? 1 : Number(endRole.roleId) + 1;
    let info = {
      openId,
      roleId,
      avatar,
      worldId: Math.ceil(roleId / 50),
      nickName,
      diamonds: 2000,
      lockArr: [1, 2, 3, 4, 5, 6],
      ranksArr: [
        [1, 2, 3, 4, 5, 0],
        [1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
      ],
      regIp: ip,
      loginIp: ip,
      createTime: abiao_utils.date()
    }
    await GUser.create(info);
    await guard.sendEmail(roleId, 1, 1, "新人福利", "钻石x2000", '[{\"type\":\"1\",\"min\":\"2000\",\"max\":\"2000\"}]');

    await guard.sendEmail(roleId, 1, 2, "游戏公告", "游戏目前属于玩法demo测试阶段，因为我们不是很清楚这类玩法是否能让大众接受，如果您对游戏后续开发有不错的建议可以加Q群：439976203", '[]');

  } else {
    roleId = UserRes.roleId;
    if (!UserRes.status) {
      throw new Result(Code.Fail, '角色被封禁!');
    }
  }

  let signRes = await GSign.findOne({ roleId });

  if (!signRes) {
    let signInfo = {
      roleId,
      signDay: 1,
      signArr: [
        { day: 1, name: "第一天", desc: "钻石x100", rewardArr: '[{\"type\":\"1\",\"min\":\"100\",\"max\":\"100\"}]' },
        { day: 2, name: "第二天", desc: "钻石x200", rewardArr: '[{\"type\":\"1\",\"min\":\"200\",\"max\":\"200\"}]' },
        { day: 3, name: "第三天", desc: "钻石x300", rewardArr: '[{\"type\":\"1\",\"min\":\"300\",\"max\":\"300\"}]' },
        { day: 4, name: "第四天", desc: "钻石x400", rewardArr: '[{\"type\":\"1\",\"min\":\"400\",\"max\":\"400\"}]' },
        { day: 5, name: "第五天", desc: "钻石x500", rewardArr: '[{\"type\":\"1\",\"min\":\"500\",\"max\":\"500\"}]' },
        { day: 6, name: "第六天", desc: "钻石x600", rewardArr: '[{\"type\":\"1\",\"min\":\"600\",\"max\":\"600\"}]' },
        { day: 7, name: "第七天", desc: "钻石x1000", rewardArr: '[{\"type\":\"1\",\"min\":\"1000\",\"max\":\"1000\"}]' },
      ],
      updateTime: abiao_utils.date(),
      createTime: abiao_utils.date()
    }
    await GSign.create(signInfo);
  }

  let victoryData: any = await utils.get_all_json("guard/victory.json");
  // console.log(victoryData);
  for (const interator of victoryData) {
    let victoryRes: any = await Victory.findOne({ roleId, victoryId: interator.id });
    console.log(victoryRes)
    if (!victoryRes) {
      let info = {
        roleId,
        victoryId: interator.id,
        isRecive: false,
        updateTime: abiao_utils.date(),
        createTime: abiao_utils.date(),
      }
      await Victory.create(info);
    }
  }

  let bagData: any = await utils.get_all_json("guard/bag.json");
  // console.log(victoryData);
  for (const interator of bagData) {
    let bagRes: any = await GBag.findOne({ roleId, id: interator.id });
    if (!bagRes) {
      let info = {
        roleId,
        id: interator.id,
        time: 0,
        maxTime: interator.maxTime,
        cost: interator.cost,
      }
      await GBag.create(info);
    }
  }

  let token = JWT.generate({ roleId });
  await GUser.updateOne({ roleId }, {
    loginIp: ip, token, updateTime: abiao_utils.date()
  });

  await guard.barrackInit(roleId);
  await guard.dailyTaskInit(roleId);

  let userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  let victoryRes = await Victory.find({ roleId });
  let emailRes = await Email.find({ roleId, isDel: false });
  signRes = await GSign.findOne({ roleId });
  let bagRes = await GBag.find({ roleId });
  let dailyTaskRes = await GDailyTask.find({ roleId });

  return res.json({ code: Code.Succ, message: "进入游戏", data: { userRes, barrackRes, treasureRes, victoryRes, emailRes, signRes, bagRes, dailyTaskRes, token, } });
})

/**
 * 修补
 */
guardRoute.post("/bagUpdate", async (req, res) => {
  let { roleId, id, type } = req.body;

  let userRes = await GUser.findOne({ roleId });
  let bagOneRes: any = await GBag.findOne({ roleId, id });

  if (type == 1) {
    if (userRes['diamonds'] < bagOneRes['cost']) {
      throw new Result(Code.Fail, '钻石不足!');
    }

    if (bagOneRes['time'] >= bagOneRes['maxTime']) {
      throw new Result(Code.Fail, '已达上限!');
    }

    await GUser.updateOne({ roleId }, { diamonds: userRes['diamonds'] - bagOneRes['cost'], updateTime: abiao_utils.date() });

    await GBag.updateOne({ roleId, id }, { time: bagOneRes['time'] + 1 });

  } else {

    if (bagOneRes['time'] < 1) {
      throw new Result(Code.Fail, '次数上限!');
    }

    await GBag.updateOne({ roleId, id }, { time: bagOneRes['time'] - 1 });

  }

  userRes = await GUser.findOne({ roleId });
  let bagRes = await GBag.find({ roleId });

  return res.json({ code: Code.Succ, message: "修补成功!", data: { userRes, bagRes } });
})

/**
 * 解锁
 */
guardRoute.post("/unLock", async (req, res) => {
  let { roleId, id, needDia } = req.body;

  let userRes = await GUser.findOne({ roleId });

  if (userRes['diamonds'] < needDia) {
    throw new Result(Code.Fail, '钻石不足!');
  }

  let bRes = await Barrack.findOne({ roleId, id });

  if (bRes['lock'] == false) {
    throw new Result(Code.Fail, '已经解锁!');
  }

  userRes['lockArr'].push(id);

  await GUser.updateOne({ roleId }, { diamonds: userRes['diamonds'] - needDia, lockArr: userRes['lockArr'], updateTime: abiao_utils.date() });

  await Barrack.updateOne({ roleId, id }, { lock: false });

  userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });

  return res.json({ code: Code.Succ, message: "解锁成功!", data: { userRes, barrackRes } });
})

/**
 * 出战或休息
 */
guardRoute.post("/setState", async (req, res) => {
  let { roleId, id, ranks } = req.body;

  // if (Number(id) == 1) {

  //   return res.json({ code: Code.Succ, message: "必须英雄!" });
  // }

  let userRes = await GUser.findOne({ roleId });

  let ranksList = userRes['ranksArr'][ranks];

  if (ranksList.indexOf(Number(id)) != -1 || ranksList.indexOf(id) != -1) {
    for (let i = 0; i < ranksList.length; i++) {
      if (ranksList[i] == id) {
        ranksList[i] = 0;
        break;
      }
    }

  } else {

    for (let i = 0; i < ranksList.length; i++) {
      if (ranksList[i] == 0) {
        ranksList[i] = id;
        break;
      }
    }
  }

  userRes['ranksArr'][ranks] = ranksList;

  await GUser.updateOne({ roleId }, { ranksArr: userRes['ranksArr'], updateTime: abiao_utils.date() });

  userRes = await GUser.findOne({ roleId });
  return res.json({ code: Code.Succ, message: "操作成功!", data: { userRes } });
})

/**
 * 获取宝箱
 */
guardRoute.post("/getTreasure", async (req, res) => {
  let { roleId, id, score } = req.body;
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  let userRes = await GUser.findOne({ roleId });
  if (userRes['score'] < score) {
    await GUser.updateOne({ roleId }, { score });
  }

  let week = utils.getNowWeek(); //当前是今年的第几周
  let wScore = userRes['wScore'];
  if (week != userRes['sWeek']) {
    wScore = 0;
  }
  if (userRes['wScore'] < score) {
    await GUser.updateOne({ roleId }, { wScore: score, sWeek: week })
  }

  if (id > -1) {
    let len = 0;
    treasureRes.forEach(ele => {
      if (ele['step'] < 4) {
        len++;
      }
    })

    if (len >= 4) {
      throw new Result(Code.Fail, '宝箱栏最多放四个!');
    }

    let step = (Number(id) == 1) ? 3 : 1;
    let info = {
      treasureId: Number(id),
      roleId,
      step: step,
      openTime: 0,
      updateTime: abiao_utils.date(1),
      createTime: abiao_utils.date(1),
    }
    await Treasure.create(info);

  }

  treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  return res.json({ code: Code.Succ, message: "操作成功!", data: { treasureRes } });
})

/**
 * 开启宝箱
 */
guardRoute.post("/openTreasure", async (req, res) => {
  let { roleId, id, uid } = req.body;
  let tRes = await Treasure.findOne({ roleId, _id: uid });

  if (!tRes) {
    throw new Result(Code.Fail, '不存在改宝箱!');
  }
  if (tRes['step'] >= 3) {
    throw new Result(Code.Fail, '宝箱已经开启完成!');
  }

  let now = abiao_utils.date(4);
  let treasureD: any = await utils.get_id_json("guard/treasure.json", id, "id");

  await Treasure.updateOne({ roleId, _id: uid }, { step: 2, openTime: Number(now) + Number(treasureD['time']) });

  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  return res.json({ code: Code.Succ, message: "操作成功!", data: { treasureRes } });

})

/**
 * 加速宝箱开启
 */
guardRoute.post("/accelerate", async (req, res) => {

  let { roleId, uid, needD } = req.body;
  let tRes = await Treasure.findOne({ roleId, _id: uid });

  let userRes = await GUser.findOne({ roleId });

  let needDia = needD || 1; //消耗钻石数

  if (userRes['diamonds'] < needDia) {
    throw new Result(Code.Fail, '钻石不足!');
  }

  if (!tRes) {
    throw new Result(Code.Fail, '不存在改宝箱!');
  }
  if (tRes['step'] >= 3) {
    throw new Result(Code.Fail, '宝箱已经开启完成!');
  }

  await GUser.updateOne({ roleId }, { diamonds: userRes['diamonds'] - needDia, updateTime: abiao_utils.date() });

  await Treasure.updateOne({ roleId, _id: uid }, { step: 2, openTime: Number(tRes['openTime']) - (60 * needDia), updateTime: abiao_utils.date() });

  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);

  userRes = await GUser.findOne({ roleId });

  return res.json({ code: Code.Succ, message: "操作成功!", data: { userRes, treasureRes } });

})

/**
 * 领取奖励
 */
guardRoute.post("/getReward", async (req, res) => {

  let { roleId, id, uid } = req.body;

  let tRes = await Treasure.findOne({ roleId, treasureId: id });

  if (!tRes) {
    throw new Result(Code.Fail, '不存在改宝箱!');
  }

  let treasureD: any = await utils.get_id_json("guard/treasure.json", id, "id");
  // console.log(treasureD)
  let rewardArr = JSON.parse(treasureD.rewardArr);
  console.log(rewardArr);
  let arr = [];
  rewardArr.forEach(element => {
    if (element) {
      switch (element['type']) {
        case "1":
          let num = abiao_utils.getRandom(Number(element['min']), Number(element['max']));
          arr.push({ type: 1, num, id: 0 })
          break;
        case "2":
          let id = abiao_utils.getRandom(1, 6);
          arr.push({ type: 2, num: element['num'], id })
          break;
        case "3":
          id = abiao_utils.getRandom(7, 9);
          arr.push({ type: 2, num: element['num'], id })
          break;
        case "4":
          id = abiao_utils.getRandom(10, 12);
          arr.push({ type: 2, num: element['num'], id })
          break;
        case "5":
          id = abiao_utils.getRandom(13, 18);
          arr.push({ type: 2, num: element['num'], id })
          break;
      }
    }
  });
  let userRes = null;
  await arr.forEach(async (ele) => {
    if (ele) {
      if (ele.type == 1) {
        userRes = await GUser.findOne({ roleId });
        await GUser.updateOne({ roleId }, { diamonds: userRes['diamonds'] + ele.num, updateTime: abiao_utils.date() });
      } else if (ele.type == 2) {
        let bRes = await Barrack.findOne({ roleId, id: ele.id });
        await Barrack.updateOne({ roleId, id: ele.id }, { fragment: Number(bRes['fragment']) + Number(ele.num), updateTime: abiao_utils.date() });
      }
    }
  });

  await Treasure.updateOne({ roleId, _id: uid }, { step: 4, openTime: 0, updateTime: abiao_utils.date() });

  userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);

  return res.json({ code: Code.Succ, message: "操作成功!", data: { arr, userRes, barrackRes, treasureRes } });

})

/**
 * 结算
 */
guardRoute.post("/integral", async (req, res) => {
  let { roleId, type } = req.body;
  let userRes = await GUser.findOne({ roleId });
  let integral = userRes['integral'];
  let victoryNum = userRes['victoryNum'];
  let wIntegral = userRes['wIntegral'];


  let week = utils.getNowWeek();  //当前是今年的第几周

  if (week != userRes['iWeek']) {
    wIntegral = 0;
  }

  if (type == 1) {
    // await GUser.updateOne({ roleId }, { integral: userRes['integral'] + 2, victoryNum: userRes['victoryNum'] + 1 });
    integral = userRes['integral'] + 2;
    victoryNum = userRes['victoryNum'] + 1;
    wIntegral += 2;
  } else if (type == 2) {
    // await GUser.updateOne({ roleId }, { integral: Math.max(0, userRes['integral'] - 2) });
    integral = Math.max(0, userRes['integral'] - 2);
    wIntegral -= 2;
    if (wIntegral < 0) {
      wIntegral = 0;
    }
  }

  await GUser.updateOne({ roleId }, { integral, wIntegral, iWeek: week, victoryNum });
  userRes = await GUser.findOne({ roleId });
  return res.json({ code: Code.Succ, data: { userRes } });
})

/**
 * 引导加一
 */
guardRoute.post("/guide", async (req, res) => {
  let { roleId } = req.body;
  let userRes = await GUser.findOne({ roleId });
  await GUser.updateOne({ roleId }, { guideId: 0 });
  userRes = await GUser.findOne({ roleId });
  return res.json({ code: Code.Succ, data: { userRes } });
})

/**
 * 获取累胜奖励
 */
guardRoute.post("/victory", async (req, res) => {
  let { roleId, id } = req.body;
  let userRes = await GUser.findOne({ roleId });
  let victoryD: any = await utils.get_id_json("guard/victory.json", id, "id");
  let victoryOneRes = await Victory.findOne({ roleId, victoryId: id });

  if (victoryOneRes['isRecive']) {
    throw new Result(Code.Fail, '奖励已经被领取!');
  }

  if (userRes['victoryNum'] < victoryD.target) {
    throw new Result(Code.Fail, '未达到领取目标!');
  }

  let rewardArr = JSON.parse(victoryD.rewardArr);
  console.log(rewardArr);
  let arr = [];
  rewardArr.forEach(element => {
    if (element) {
      switch (element['type']) {
        case "1":
          let num = abiao_utils.getRandom(Number(element['min']), Number(element['max']));
          arr.push({ type: 1, num, id: 0 })
          break;
        case "2":
          let id = abiao_utils.getRandom(1, 6);
          arr.push({ type: 2, num: element['num'], id })
          break;
        case "3":
          id = abiao_utils.getRandom(7, 9);
          arr.push({ type: 2, num: element['num'], id })
          break;
        case "4":
          id = abiao_utils.getRandom(10, 12);
          arr.push({ type: 2, num: element['num'], id })
          break;
        case "5":
          id = abiao_utils.getRandom(13, 18);
          arr.push({ type: 2, num: element['num'], id })
          break;
        case "6":
          arr.push({ type: 3, num: 1, id: element['num'] });
          break;
      }
    }
  });

  await arr.forEach(async (ele) => {
    if (ele) {
      if (ele.type == 1) {
        userRes = await GUser.findOne({ roleId });
        await GUser.updateOne({ roleId }, { diamonds: userRes['diamonds'] + ele.num, updateTime: abiao_utils.date() });
      } else if (ele.type == 2) {
        let bRes = await Barrack.findOne({ roleId, id: ele.id });
        await Barrack.updateOne({ roleId, id: ele.id }, { fragment: Number(bRes['fragment']) + Number(ele.num), updateTime: abiao_utils.date() });
      } else if (ele.type == 3) {
        let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
        let len = 0;
        treasureRes.forEach(ele => {
          if (ele['step'] < 4) {
            len++;
          }
        })

        if (len < 4) {
          //创建宝箱
          let step = (Number(ele.num) == 1) ? 3 : 1;
          let info = {
            treasureId: Number(ele.num),
            roleId,
            step: step,
            openTime: 0,
            updateTime: abiao_utils.date(1),
            createTime: abiao_utils.date(1),
          }
          await Treasure.create(info);
        }
      }
    }
  });

  await Victory.updateOne({ roleId, victoryId: id }, { isRecive: true });

  userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  let victoryRes = await Victory.find({ roleId });

  return res.json({ code: Code.Succ, message: "操作成功!", data: { arr, userRes, barrackRes, treasureRes, victoryRes } });
})


/**
 * 发送邮件
 */
guardRoute.post("/sendEmail", async (req, res) => {
  const { roleId, sendType, type, title, desc, rewardArr } = req.body;
  let info = {
    roleId,
    type,
    title,
    desc,
    rewardArr,
    isRecive: false,
    updateTime: abiao_utils.date(1),
    createTime: abiao_utils.date(1),
  }
  //发送给个人
  if (sendType == 1) {
    await Email.create(info);
  } else if (sendType == 2) {
    let allUser = await GUser.find({ status: true });
    allUser.forEach((ele) => {
      info.roleId = ele['roleId'];
      Email.create(info);
    })
  }
})


/**
 * 获取邮件列表
 */
guardRoute.post("/getEmailList", async (req, res) => {

  const { roleId } = req.body;

  let emailRes = await Email.find({ roleId, isDel: false });

  return res.json({ code: Code.Succ, message: "操作成功!", data: { emailRes } });
})

/**
 * 领取邮件奖励
 */
guardRoute.post("/lqEmail", async (req, res) => {

  const { roleId, uid } = req.body;
  console.log(uid)
  let emailOneRes = await Email.findOne({ _id: uid, isDel: false });
  if (!emailOneRes) {
    throw new Result(Code.Fail, '未找到该邮件，或已被删除!');
  }

  if (emailOneRes['isRecive']) {
    throw new Result(Code.Fail, '该邮件已被领取!');
  }

  console.log(emailOneRes['rewardArr'])

  let arr = await guard.sendProp(roleId, JSON.parse(emailOneRes['rewardArr']));
  await Email.updateOne({ _id: uid, isDel: false }, { isRecive: true });
  let userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  let emailRes = await Email.find({ roleId, isDel: false });

  return res.json({ code: Code.Succ, message: "操作成功!", data: { arr, userRes, barrackRes, treasureRes, emailRes } });
})

/**
 * 领取邮件奖励
 */
guardRoute.post("/delEmail", async (req, res) => {

  const { roleId, uid } = req.body;
  console.log(uid)
  let emailOneRes = await Email.findOne({ _id: uid, isDel: false });
  if (!emailOneRes) {
    throw new Result(Code.Fail, '未找到该邮件，或已被删除!');
  }

  await Email.updateOne({ _id: uid, isDel: false }, { isDel: true });

  let emailRes = await Email.find({ roleId, isDel: false });

  return res.json({ code: Code.Succ, message: "操作成功!", data: { emailRes } });
})

/**
 * 一键领取
 */
guardRoute.post("/yjLq", async (req, res) => {
  const { roleId } = req.body;
  let emailRes = await Email.find({ roleId, isDel: false, isRecive: false });
  emailRes.forEach(async (ele) => {
    await guard.sendProp(roleId, JSON.parse(ele['rewardArr']));
    // await Email.updateOne({ _id: ele._id, isDel: false });
  })
  await Email.updateMany({ roleId }, { isRecive: true, updateTime: abiao_utils.date(1) });
  let userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  emailRes = await Email.find({ roleId, isDel: false });

  return res.json({ code: Code.Succ, message: "领取成功!", data: { userRes, barrackRes, treasureRes, emailRes } });
})

/**
 * 一键删除
 */
guardRoute.post("/yjDel", async (req, res) => {
  const { roleId } = req.body;
  await Email.updateMany({ roleId }, { isDel: true, updateTime: abiao_utils.date(1) });
  let emailRes = await Email.find({ roleId, isDel: false });
  return res.json({ code: Code.Succ, message: "操作成功!", data: { emailRes } });
})

/**
 * 修改昵称
 */
guardRoute.post("/updateNickName", async (req, res) => {
  const { roleId, nickName } = req.body;
  await GUser.updateOne({ roleId }, { nickName });
  let userRes = await GUser.findOne({ roleId });
  return res.json({ code: Code.Succ, message: "操作成功!", data: { userRes } });
})

/**
 * 兑换码
 */
guardRoute.post("/exchange", async (req, res) => {
  const { roleId, id } = req.body;
  let exchangeRes = await Exchange.findOne({ id });

  if (!exchangeRes) {
    throw new Result(Code.Fail, '该兑换码不存在!');
  }

  if (exchangeRes['isUse']) {
    throw new Result(Code.Fail, '该兑换码已被使用!');
  }

  let exchangeLog = await ExchangeLog.findOne({ roleId, id });
  if (exchangeLog) {
    throw new Result(Code.Fail, '你已兑换过!');
  }

  let arr = await guard.sendProp(roleId, JSON.parse(exchangeRes['rewardArr']));

  if (exchangeRes['type'] == 2) {
    await Exchange.updateOne({ id }, { isUse: true });
  }

  let info = {
    id,
    roleId,
    createTime: abiao_utils.date(1)
  }
  await ExchangeLog.create(info);
  let userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  let emailRes = await Email.find({ roleId, isDel: false });

  return res.json({ code: Code.Succ, message: "操作成功!", data: { arr, userRes, barrackRes, treasureRes, emailRes } });
})

/**
 * 点击签到
 */
guardRoute.post("/sign", async (req, res) => {
  const { roleId } = req.body;
  let signRes = await GSign.findOne({ roleId });
  let nowDate = abiao_utils.date(2);

  if (signRes['updateTime'] == nowDate) {
    throw new Result(Code.Fail, '今日已经签到!');
  }
  let sRes = signRes['signArr'][signRes['signDay'] - 1];

  let arr = await guard.sendProp(roleId, JSON.parse(sRes['rewardArr']));
  let nextSignDay = signRes['signDay'] + 1;
  if (nextSignDay > 7) {
    nextSignDay = 1;
  }
  await GSign.updateOne({ roleId }, { signDay: nextSignDay, updateTime: abiao_utils.date(2) });

  let userRes = await GUser.findOne({ roleId });

  signRes = await GSign.findOne({ roleId });

  return res.json({ code: Code.Succ, message: "签到成功!", data: { arr, userRes, signRes } });
})



/**
 * 获取排名列表
 */
guardRoute.post("/rankList", async (req, res) => {
  const { roleId } = req.body;

  // let userRes: any = await GUser.findOne({ roleId });

  let pvpList: any = await Redis.get("integral:rank");
  if (pvpList) {
    pvpList = JSON.parse(pvpList);
  } else {
    pvpList = await guard.getRankData({ status: true }, { "integral": -1 }, roleId, "integral");
  }
  let index: any = await Redis.get("integral:rank:" + roleId);

  if (pvpList.length > 0) {
    pvpList = pvpList[index] || [];
  }

  let mxList: any = await Redis.get("score:rank");
  if (mxList) {
    mxList = JSON.parse(mxList);
  } else {
    mxList = await guard.getRankData({ status: true }, { "score": -1 }, roleId, "score");
  }
  // console.log(index);
  // console.log(mxList);
  index = await Redis.get("score:rank:" + roleId);

  if (mxList.length > 0)
    mxList = mxList[index] || [];

  let week = await utils.getNowWeek(); //当前是今年的第几周

  // let wPvpList = await GUser.find({ status: true, iWeek: week, worldId: userRes.worldId }).sort({ "wIntegral": -1 }).limit(50); //周 pvp排名

  let wPvpList: any = await Redis.get("wIntegral:rank");
  if (wPvpList) {
    wPvpList = JSON.parse(wPvpList);
  } else {
    wPvpList = await guard.getRankData({ status: true, iWeek: week }, { "wIntegral": -1 }, roleId, "wIntegral");
  }
  index = await Redis.get("wIntegral:rank:" + roleId);
  console.log(index);
  if (wPvpList.length > 0) {
    wPvpList = wPvpList[index] || [];
  }

  // let wMxList = await GUser.find({ status: true, sWeek: week, worldId: userRes.worldId }).sort({ "wScore": -1 }).limit(50); //周 冒险排名

  let wMxList: any = await Redis.get("wScore:rank");

  if (wMxList) {
    wMxList = JSON.parse(wMxList);
  } else {
    wMxList = await guard.getRankData({ status: true, sWeek: week }, { "wScore": -1 }, roleId, "wScore");
  }
  index = await Redis.get("wScore:rank:" + roleId);
  // console.log(index);
  if (wMxList.length > 0) {
    wMxList = wMxList[index] || [];
  }
  return res.json({ code: Code.Succ, message: "获取成功!", data: { pvpList, mxList, wPvpList, wMxList } });
})

/**
 * 更新每日任务进度
 */
guardRoute.post("/updateDailyTask", async (req, res) => {
  const { roleId, id } = req.body;
  if (!roleId || !id) {
    throw new Result(Code.Fail, '缺少参数!');
  }
  await GDailyTask.findOneAndUpdate({ roleId, id }, { $inc: { progress: 1 } });
  let dailyTaskRes = await GDailyTask.find({ roleId });
  return res.json({ code: Code.Succ, message: "操作成功!", data: { dailyTaskRes } });
})

/**
 * 领取每日任务奖励
 */
guardRoute.post("/receiveDailyTask", async (req, res) => {
  const { roleId, id } = req.body;
  if (!roleId || !id) {
    throw new Result(Code.Fail, '缺少参数!');
  }
  let task: any = await GDailyTask.findOne({ roleId, id });
  if (task.isRecive) {
    throw new Result(Code.Fail, '已经领取!');
  }
  let json: any = await utils.get_id_json("guard/renwubiao.json", id, "gradeID");

  // if (task.progress >= json.Conditions) {
  let reward = await JSON.parse(json.activityReward);
  await GDailyTask.updateOne({ roleId, id }, { isRecive: true });
  let rewardArr = await guard.sendProp(roleId, reward);
  // } else {
  //   throw new Result(Code.Fail, '未达到目标!');
  // }8*1.5
  let dailyTaskRes = await GDailyTask.find({ roleId });
  let userRes = await GUser.findOne({ roleId });
  return res.json({ code: Code.Succ, message: "操作成功!", data: { dailyTaskRes, userRes, rewardArr } });
})

/**
 * 关卡结算奖励
 */
guardRoute.post("/settlement", async (req, res) => {
  const { roleId, level, star } = req.body;
  if (!roleId || !level || !star) {
    throw new Result(Code.Fail, '缺少参数!');
  }

  let json: any = await utils.get_part_json("guard/jeisuan.json", level, "level");
  let reward = [];
  json.forEach(element => {
    if (Number(element.star) == Number(star)) {
      reward = JSON.parse(element.reward);
    }
  });
  await guard.sendProp(roleId, reward)
  let userRes = await GUser.findOne({ roleId });
  return res.json({ code: Code.Succ, message: "操作成功!", data: { userRes } });
})

/**
 * 天赋 消耗钻石
 */
guardRoute.post("/consumeTalentDiamond", async (req, res) => {
  const { roleId, id } = req.body;
  let json: any = await utils.get_id_json("guard/talent.json", id, "id");
  let userRes = await GUser.findOne({ roleId });

  let cost = Number(json['expend']);
  if (userRes['diamonds'] < cost) {
    throw new Result(Code.Fail, '钻石不足!');
  }

  await GUser.updateOne({ roleId }, { diamonds: userRes['diamonds'] - cost, updateTime: abiao_utils.date() });

  userRes['diamonds'] -= cost;

  return res.json({ code: Code.Succ, message: "操作成功!", data: { userRes } });
})

/**
 * 刷新数据
 */
guardRoute.post("/getData", async (req, res) => {
  const { roleId } = req.body;
  let userRes = await GUser.findOne({ roleId });
  let barrackRes = await Barrack.find({ roleId });
  let treasureRes = await Treasure.find({ roleId }).lt("step", 4);
  let emailRes = await Email.find({ roleId, isDel: false });
  let dailyTaskRes = await GDailyTask.find({ roleId });
  return res.json({ code: Code.Succ, message: "操作成功!", data: { userRes, barrackRes, treasureRes, emailRes, dailyTaskRes } });
})


export default guardRoute;
